package com.domain.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.domain.common.AppLogger;
import com.domain.common.Comments;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.PublishMapper;
import com.domain.dao.UsersAlipayMapper;
import com.domain.dao.UsersMapper;
import com.domain.dao.UsersWalletMapper;
import com.domain.pojo.Publish;
import com.domain.pojo.Users;
import com.domain.pojo.UsersAlipay;
import com.domain.service.AliPayService;
import com.domain.service.BillService;
import com.domain.service.PushMessageService;
import com.domain.utils.ArithmeticUtil;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.alipay.AlipayConfig;
import com.domain.utils.alipay.AlipayUtil;
import com.domain.utils.jiguang.Jdpush;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class AliPayServiceImpl implements AliPayService {
    @Autowired
    private BillService billService;

    @Autowired
    private UsersAlipayMapper usersAlipayMapper;

    @Autowired
    private PublishMapper publishMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PushMessageService pushMessageService;

    @Autowired
    private UsersWalletMapper usersWalletMapper;


    /**
     * 日志
     */
    private static Logger logger = AppLogger.getLogger(AliPayServiceImpl.class.getSimpleName(), Level.INFO.toString(), true);

    /**
     * 支付成功回调
     *
     * @param request
     * @return
     */
    //只读事务
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result return_url(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        logger.info("获取的支付宝支付返回的参数");
        try {
            AlipaySignature.rsaCheckV1(params, AlipayConfig.ALI_ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.ALI_SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    //只读事务
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result openauth(String usersId, String code) throws AlipayApiException {
        //根据前端传过来的code获取acctoken
        String acctoken = AlipayUtil.buildRequest(code);
        if (NotNullUtils.isNotNullObject(acctoken)) {
            AlipayUserInfoShareResponse response = AlipayUtil.get(acctoken);
            if (response.isSuccess()) {
                UsersAlipay u = usersAlipayMapper.selectByAlipayUsersId(response.getUserId());
                if (!NotNullUtils.isNotNullObject(u)) {
                    //添加用户的支付宝账号信息
                    UsersAlipay alipay = new UsersAlipay();
                    alipay.setId(UUIDUtils.getRandomUUID());
                    alipay.setUsersId(usersId);
                    alipay.setAlipayHeadimage(response.getAvatar());
                    alipay.setAlipayNickname(response.getNickName());
                    alipay.setAlipayName(response.getUserName());
                    alipay.setAlipayPhone(response.getPhone());
                    alipay.setAlipayUserId(response.getUserId());
                    alipay.setCreatTime(new Date());
                    usersAlipayMapper.insertSelective(alipay);
                } else {
                    u.setAlipayHeadimage(response.getAvatar());
                    u.setAlipayNickname(response.getNickName());
                    u.setAlipayName(response.getUserName());
                    u.setAlipayPhone(response.getPhone());
                    u.setAlipayUserId(response.getUserId());
                    u.setUpdateTime(new Date());
                    usersAlipayMapper.updateByPrimaryKeySelective(u);
                }
            } else {
                return Result.fail("获取用户信息失败");
            }
        } else {
            return Result.fail("acctoken为空获取用户信息失败");
        }
        return Result.success();

    }

    /**
     * 取消绑定支付宝
     *
     * @param usersId
     * @return
     */
    @Override
    public Result deleteAlipay(String usersId) {
        usersAlipayMapper.deleteByUsersId(usersId);
        return Result.success();
    }

    /**
     * @param usersId
     * @param publishId
     * @param acknowledgeUsers
     * @param type
     * @return
     */
    @Override
    public Result paySuccrss(String usersId, String publishId, String acknowledgeUsers, String money, String type) {
        logger.info("usersId++++++++++" + usersId);
        logger.info("publishId++++++++++" + publishId);
        logger.info("acknowledgeUsers++++++++++" + acknowledgeUsers);
        logger.info("money++++++++++" + money);
        logger.info("type++++++++++" + type);
        if ("1".equals(type)) {
            //发布红包支付成功生成账单信息
            logger.info("帮转红包支付生成账单信息+" + usersId);
            //支付成功添加账单信息
            billService.addBill("", usersId, "帮转红包支付", Comments.SERZERBAL_OUT, money, Const.RED_PACKAGE_ICONS);
        } else if ("2".equals(type)) {
            //修改发布得钱数
            Publish pe = publishMapper.selectByPrimaryKey(publishId);
            BigDecimal moneys = ArithmeticUtil.add(pe.getSpareTwo().toString(), money);
            pe.setSpareTwo(moneys);
            publishMapper.updateByPrimaryKeySelective(pe);
            //添加账单信息
            billService.addBill("", usersId, "帮转红包补加支付", Comments.SERZERBAL_OUT, money, Const.RED_PACKAGE_ICONS);
        } else if ("3".equals(type)) {
            //支付者信息
            Users users = usersMapper.selectByPrimaryKey(usersId);
            //推送消息至答谢的人
            String pushId = UUIDUtils.getRandomUUID();
            Jdpush.sendToAliasList(acknowledgeUsers, "您收到了一笔来自" + users.getName() + "的答谢金", "pushId", pushId, "pushType", Const.thank_you, "bigTypeKey", Const.PUBLISH_MESSAGE, "答谢金通知");
            //添加推送记录
            pushMessageService.addAcknowledgeMessage(acknowledgeUsers, usersId, "您收到了一笔来自" + users.getName() + "的答谢金", "答谢金通知", money, Const.thank_you, pushId, users.getName());
            //添加账单信息（支付人支出）
            billService.addBill("", usersId, "答谢金答谢支出", Comments.SERZERBAL_OUT, money, Const.RED_PACKAGE_ICONS);
            logger.info("答谢成功***************");
        }
        return Result.success();
    }

}
